package com.cvmars.jianyou.module.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.adapter.AddressAdapter;
import com.cvmars.jianyou.module.base.BasePictureActivity;
import com.cvmars.jianyou.ui.CircleImageView;
import com.cvmars.jianyou.utils.NetworkUtil;
import com.cvmars.jianyou.utils.QiNiuUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterCompleteActivity extends BasePictureActivity {

    @BindView(R.id.me_info_avatar)
    CircleImageView meInfoAvatar;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_info_name)
    EditText txtInfoName;
    @BindView(R.id.rl_name)
    RelativeLayout rlName;
    @BindView(R.id.txt_info_sex)
    TextView txtInfoSex;
    @BindView(R.id.rl_info_sex)
    RelativeLayout rlInfoSex;
    @BindView(R.id.txt_info_birthday)
    TextView txtInfoBirthday;
    @BindView(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    @BindView(R.id.parent_layout)
    LinearLayout parentLayout;
    AddressAdapter homeAdapter;
    @BindView(R.id.txt_info_address)
    TextView txtInfoAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    Date mCurDate;//当前选择时间
    @BindView(R.id.txt_join)
    Button txtJoin;

    int ageType = 1;

    boolean isSelectAvator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_complete);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.me_info_avatar, R.id.rl_info_sex, R.id.rl_birthday, R.id.txt_join})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.me_info_avatar:

                selectSingPic();
                break;
            case R.id.rl_info_sex:
                onSex();
                break;
            case R.id.rl_birthday:
                onDate();
                break;

            case R.id.txt_join:

                String name = txtInfoName.getText().toString();
                String age = txtInfoBirthday.getText().toString();
                String address = txtInfoAddress.getText().toString();

                if (!isSelectAvator) {
                    ToastUtils.show("请选择头像");
                    return;
                }

                if (TextUtils.isEmpty(name)) {

                    ToastUtils.show("请输入昵称");
                    return;
                }


                if (TextUtils.isEmpty(age)) {

                    ToastUtils.show("请选择日期");
                    return;
                }

                if (TextUtils.isEmpty(address)) {

                    ToastUtils.show("请选择地址");
                    return;
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("address_home", address);
                map.put("age", age);
                map.put("gender", ageType + "");
                map.put("name", name);
                getLoadDialogAndShow();
                onUpdateInfo(false, map);

                break;
        }
    }


    private void onAddress() {
        View popupView = LayoutInflater.from(RegisterCompleteActivity.this).inflate(R.layout.layout_pop_address, null);
        PopupWindow popupWindow = showPopWindow(popupView, findViewById(R.id.parent_layout));
        initPopList(popupWindow, popupView);
    }

    private void initPopList(final PopupWindow popupWindow, View popupView) {

        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (popupWindow != null) {

                    popupWindow.dismiss();
                }

            }
        });

        RecyclerView listAddress = popupView.findViewById(R.id.list_address);
        final List<String> list = new ArrayList<>();
        list.add("琴亭镇");
        list.add("坊楼镇");
        list.add("良坊镇");
        list.add("路口镇");
        list.add("升坊镇");
        list.add("湖上乡");
        list.add("神泉乡");
        list.add("三板桥乡");
        list.add("南岭乡");
        list.add("荷塘乡");
        list.add("闪石乡");
        list.add("高洲乡");
        list.add("六市乡");
        homeAdapter = new AddressAdapter(R.layout.item_address, list);
        listAddress.setLayoutManager(new LinearLayoutManager(this));
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                String address = list.get(position);
                txtInfoAddress.setText(address);
                popupWindow.dismiss();
            }
        });
        listAddress.setAdapter(homeAdapter);
    }

    private void onSex() {

        View popupView = LayoutInflater.from(RegisterCompleteActivity.this).inflate(R.layout.layout_pop_sex, null);
        final PopupWindow popupWindow = showPopWindow(popupView, findViewById(R.id.parent_layout));
        View man = popupView.findViewById(R.id.txt_sex_man);
        View women = popupView.findViewById(R.id.txt_sex_women);
        man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                txtInfoSex.setText("男");
                ageType = 1;
                if (popupWindow != null) {

                    popupWindow.dismiss();
                }
            }
        });
        women.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                txtInfoSex.setText("女");
                ageType = 2;
                if (popupWindow != null) {

                    popupWindow.dismiss();
                }
            }
        });

        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (popupWindow != null) {

                    popupWindow.dismiss();
                }

            }
        });
    }

    /**
     * 选择日期
     */
    public void onDate() {

        TimePickerView pvTime;
        //时间选择器 ，自定义布局
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(selectedDate.get(Calendar.YEAR) - 80, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.get(Calendar.YEAR), 11, 28);
        if (mCurDate != null) {
            selectedDate.setTime(mCurDate);
        } else {
            Calendar init = Calendar.getInstance();
            init.set(init.get(Calendar.YEAR) - 23, 11, 28);
            selectedDate.setTime(init.getTime());
        }
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                mCurDate = date;
                int age = (new Date().getYear() - date.getYear());
                txtInfoBirthday.setText(age + "");
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.parseColor("#dddddd"))
                .setCancelColor(Color.parseColor("#666666"))
                .setSubmitColor(Color.parseColor("#666666"))
                .setContentTextSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
        pvTime.show();

    }


    private void onUpdateInfo(final boolean selectAvator, Map<String, String> map) {
        HttpUtils.getInstance().toSubscribe(Api.getInstance().UpdataInfoUseInfo(map)
                , new SimpleSubscriber<HttpResult<UserModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserModel> o) {


                        if (selectAvator) {
                            isSelectAvator = true;
                        } else {
                            getLoadDialogAndDismiss();
                            goActivity(null, HomeActivity.class);
                            finish();
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    if (localMedias != null && localMedias.size() > 0) {

                        if (NetworkUtil.isNetworkConnected(this)) {


                            Glide.with(RegisterCompleteActivity.this)
                                    .load(localMedias.get(0).getPath())
                                    .into(meInfoAvatar);

                            List<ImageModel> models = new ArrayList<>();
                            ImageModel model = new ImageModel();
                            model.imgPath = localMedias.get(0).getCutPath();
                            models.add(model);
                            QiNiuUtils.getInstance().initImage(models, handler);
                        } else {

                        }
                    }
                    break;
            }
        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            List<ImageModel> list = (List<ImageModel>) msg.obj;

            if (list != null && list.size() > 0) {

                HashMap<String, String> map = new HashMap<>();
                map.put("avatar_url", list.get(0).uploadPath);
                onUpdateInfo(true, map);
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();

        PictureFileUtils.deleteCacheDirFile(this);
    }

    @OnClick(R.id.rl_address)
    public void onViewClicked() {

        onAddress();
    }

}
